// pages/myClassStudent/myClassStudent.js
let klassModel = require('../../models/klass.js')
let userModel = require('../../models/user.js')
let request = require('../../operation/operation.js')
let bxt = require('../../utils/bxt.js')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    students:[],
    canDel:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.initUserPower()
    this.getClassStudents()

    getApp().notificationCenter.register(bxt.DELETE_STUDENT_MESSAGE, this, "handleDelStudentMessage");
  },

  onUnload:function() {
    getApp().notificationCenter.remove(bxt.DELETE_STUDENT_MESSAGE, this)
  },

  onShowStudentInfo:function(event) {
    if (this.data.canDel) {
      getApp().globalData.param = event.currentTarget.dataset.student

      wx.navigateTo({
        url: '../studentInfo/studentInfo?canDel=true'
      })
    }
  },

  initUserPower:function() {
    this.setData({
      canDel: userModel.checkUserManager()
    })
  },

  getClassStudents:function() {
    let currentClass = klassModel.getCurrentClass(), that = this
    request.getRequest('/students?klassSid=' + currentClass.sid, {}, true)
      .then(res => {
        var data = res.data;
        if (request.SUCCESSED == data.status) {
          that.setData({
            students:data.items
          })
        } else {
          wx.showToast({
            title: data.msg,
            iocn: 'none'
          })
        }
      })
      .catch(e => {
        console.log(e)
      })
  },

  handleDelStudentMessage: function (object) {
    let students = this.data.students

    for(let index = 0,length = students.length; index < length; index++) {
      if (object.student.sid == students[index].sid) {
        students.splice(index, 1)
        break
      }
    }

    this.setData({
      students:students
    })
  }

})